import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    
    // 如果响应格式包含success字段
    if (Object.prototype.hasOwnProperty.call(res, 'success')) {
      if (res.success) {
        return res
      } else {
        Message({
          message: res.message || '请求失败',
          type: 'error',
          duration: 5000
        })
        return Promise.reject(new Error(res.message || '请求失败'))
      }
    }
    
    // 兼容其他响应格式
    return res
  },
  error => {
    console.error('响应错误:', error)
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          Message({
            message: '登录已过期，请重新登录',
            type: 'error',
            duration: 5000
          })
          localStorage.removeItem('token')
          localStorage.removeItem('user')
          localStorage.removeItem('roles')
          localStorage.removeItem('expireTime')
          router.push('/login')
          break
        case 403:
          Message({
            message: '权限不足',
            type: 'error',
            duration: 5000
          })
          break
        case 500:
          Message({
            message: '服务器内部错误',
            type: 'error',
            duration: 5000
          })
          break
        default:
          Message({
            message: (data && data.message) || error.message || '请求失败',
            type: 'error',
            duration: 5000
          })
      }
    } else {
      Message({
        message: '网络错误，请检查网络连接',
        type: 'error',
        duration: 5000
      })
    }
    
    return Promise.reject(error)
  }
)

export default service